package com.kn.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kn.common.exception.UserException;
import com.kn.common.model.PageBean;
import com.kn.common.model.R;
import com.kn.common.model.RCode;
import com.kn.common.model.RPage;
import com.kn.sys.dto.RoleAllDto;
import com.kn.sys.dto.RoleDto;
import com.kn.sys.mapper.RoleMapper;
import com.kn.sys.model.Role;
import com.kn.sys.model.RoleExample;
import com.kn.sys.model.User;
import com.kn.sys.service.RoleService;
import com.kn.sys.untils.CopyBean;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author zhoudf
 * @create 2021-03-09 11:47
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
    private final RoleMapper roleMapper;
    @Override
    public R findAllRole() {

        List<Role> roles = roleMapper.selectByExample(null);
        List<RoleAllDto> roleAllDtos = CopyBean.copyBean(RoleAllDto::new, roles);
        return R.ok(roleAllDtos);
    }

    @Override
    public R list(PageBean pageBean, String name) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria().andIsdelEqualTo(false);
        if(StringUtils.isEmpty(name)){
            criteria.andCnameLike("%"+name+"%");

        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getSize());
        PageInfo<Role> rolePageInfo = new PageInfo<>(roleMapper.selectByExample(roleExample));
        return R.ok(new RPage(rolePageInfo.getTotal(),CopyBean.copyBean(RoleDto::new,rolePageInfo.getList())));
    }

    @Override
    public R add(RoleDto roleDto) {
        isExist(roleDto);
        roleMapper.insertSelective(CopyBean.copyBean(Role::new,roleDto));
        return R.ok();
    }

    @Override
    public R delete(Long id) {
        Role role = new Role();
        role.setId(id);
        role.setIsdel(true);
        roleMapper.updateByPrimaryKeySelective(role);
        return R.ok();
    }

    @Override
    public R edit(Long id, RoleDto roleDto) {
        Role role = roleMapper.selectByPrimaryKey(id);

        if(role==null){
            throw new UserException(RCode.NOT_EXIST_ROLE);
        }
        BeanUtils.copyProperties(roleDto,role);
        role.setId(id);
        role.setOptime(new Date());
        roleMapper.updateByPrimaryKeySelective(role);
        return R.ok();

    }

    private void isExist(RoleDto roleDto) {
        RoleExample example = new RoleExample();
        example.createCriteria().andCnameEqualTo(roleDto.getCname());
        long l = roleMapper.countByExample(example);
        if(l>0){
            throw new UserException(RCode.EXIST_ROLE);
        }
    }
}
